package ${package}.utils;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import java.util.Map;
import java.util.Set;

/**
 */

public class CommonUtils {

    /**
     * 将字符串转为set
     * @param source 源字符串
     * @return set集合
     */
    public static Set<String> stringToSet(String source){

        Set<String> set = Sets.newConcurrentHashSet();

        if(StringUtils.isEmpty(source)){
            return set;
        }

        Iterable<String> split = Splitter.on(",").omitEmptyStrings().trimResults().split(source);

        return Sets.newConcurrentHashSet(split);

    }

    /**
     * 将字符串转为map
     * @param source 源字符串
     * @return map集合
     */
    public static Map<String,String> stringToMap(String source){

        Map<String,String> map = Maps.newHashMap();

        if(StringUtils.isEmpty(source)){
            return map;
        }

        return Splitter.on(",").withKeyValueSeparator("_").split(source);
    }

    /**
     * 直接使用guava
     * @param source
     * @return
     */
    public static Map<String,String> stringToNormalMap(String source){

        Map<String,String> map = stringToMap(source);

        Map<String,String> resultMap = new HashedMap();

        for(Map.Entry<String,String> entry : map.entrySet()){

            resultMap.put(entry.getKey(),entry.getValue());
        }

        return resultMap;
    }

    /**
     * 将set转为字符串
     * @param source 源集合
     * @return 字符串
     */
    public static String setToString(Set<String> source){

        if(CollectionUtils.isEmpty(source)){
            return null;
        }

        return Joiner.on(",").join(source);

    }

    /**
     * 将map转为字符串
     * @param source 源map
     * @return 字符串
     */
    public static String mapToString(Map<String,String> source){
        if (source == null || source.size() == 0)
        {
            return null;
        }

        return Joiner.on(",").withKeyValueSeparator("_").join(source);
    }
}
